package ru.spb.osll.myfit.client.widget;

import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.TextBox;

public class FlexTableWidget extends TableWidget {

  public FlexTableWidget(GWTWidgetFactory gwtWidgetFactory, Table table) {
    super(gwtWidgetFactory, table);
  }

  protected void refreshTable(FlexTable table) {
    if (table.getRowCount() == 0) {
      m_flexTable.removeFromParent();
    }
  }

  @Override
  protected void addNewRow(int row) {
    m_flexTable.insertRow(row);
    TextBox tb = createTextEdit(new TableCell());
    tb.setReadOnly(false);
    m_flexTable.setWidget(row, 0, tb);
    updateWidth();
  }

  @Override
  protected void addNewCell(int row, int cell) {
    int cellCount = m_flexTable.getCellCount(row);
    m_flexTable.getFlexCellFormatter().setColSpan(row, cellCount - 1, 0);
    if (cell < cellCount) {
      m_flexTable.insertCell(row, cell);
    }
    TextBox tb = createTextEdit(new TableCell());
    tb.setReadOnly(false);
    m_flexTable.setWidget(row, cell, tb);
    updateWidth();
  }

  @Override
  protected void deleteCell(int row, int cell) {
    m_flexTable.removeCell(row, cell);
    if(m_flexTable.getCellCount(row) == 0){
      m_flexTable.removeRow(row);
    }
    updateWidth();
  }

  @Override
  protected void setReadOnly(boolean isReadOnly) {
    int rowCount = m_flexTable.getRowCount();
    for (int i = 0; i < rowCount; i++) {
      int cellCount = m_flexTable.getCellCount(i);
      for (int j = 0; j < cellCount; ++j) {
        try {
          TextBox tb = ((TextBox) m_flexTable.getWidget(i, j));
          tb.setReadOnly(isReadOnly || (j % 2 == 0));
        } catch (Exception ex) {
        }
      }
    }
  }

  protected void tuneMenu() {
    m_deleteRowItem.setVisible(m_selectedRow >= 1);
    m_deleteCellItem.setVisible(m_selectedRow >= 1);
    m_addCellItem.setVisible(m_selectedRow >= 1);
  }

  @Override
  protected void setSpecifiedStyles(int row, int cell) {
  }
}
